<template>
	<view class="viewBg">
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					日志标题
				</view>
				<view class="uni-list-cell-db">
					<!-- 日志标题 -->
					<input class="uni-input" placeholder="日志标题" :value="eventTitle" @blur="bindInputBlur" @focus="hiddenText"/>
				</view>
			</view>
		</view>
		
		<!-- 记录时间 -->
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-left">
					记录时间
				</view>
				<view class="uni-list-cell-db">
					<picker mode="date" placeholder="记录时间" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
						<view class="uni-input">{{date}}</view>
					</picker>
				</view>
			</view>
		</view>
		<!-- 列表 -->
		<view class="uni-list">
			<view class="uni-list-cell" v-for="(item, index) in list" :key="index">
				<view class="uni-list-cell-navigate uni-navigate-right" @click="showPicker(index)">
					<text class="cell-text">{{ item.title }}</text>
					<text class="cell-detail">{{ item.selectedLabel }}</text>
				</view>
			</view>
		</view>
		<!-- 分割线 -->
		<view class="lineH20"></view>
		<!-- 问题 -->
		<input class="uni-input" placeholder="问题描述" :value="eventTitle" @blur="bindInputBlur" @focus="hiddenText"/>
		<view class="lineH1"></view>
		<!-- 详细描述 -->
		<view class="uni-textarea"><textarea placeholder="详细说明" :value="eventDesc" @blur="bindTextAreaBlur" @focus="hiddenText"/></view>
		<view class="uni-list">
			<view class="uni-list-cell">
				<view class="uni-list-cell-navigate uni-navigate-right" @click="seleceLocation">
					<text class="cell-text" style="max-width: 600upx">{{address}}</text>
					<text class="cell-detail" v-if="location === null" style="width: 100upx">请选择</text>
					<text class="cell-detail" v-if="location !== null" style="width: 100upx">已选择</text>
				</view>
			</view>
		</view>
		<!-- 上传图片 -->
		<view class="feedback-body feedback-uploader">
			<view class="uni-uploader">
				<view class="uni-uploader-head">
					<view class="uni-uploader-title">点击上传图片</view>
					<view class="uni-uploader-info">{{ imageList.length }}/6</view>
				</view>
				<view class="uni-uploader-body">
					<view class="uni-uploader__files">
						<block v-for="(image, index) in imageList" :key="index">
							<view class="uni-uploader__file" style="position: relative;">
								<image class="uni-uploader__img" :src="image" @tap="previewImage(index)"></image>
								<view class="close-view" @click="close(index)">x</view>
							</view>
						</block>
						<view class="uni-uploader__input-box" v-show="imageList.length < 6"><view class="uni-uploader__input" @tap="chooseImg"></view></view>
					</view>
				</view>
			</view>
		</view>
		<view class="button-sp-area" v-if="videoPath === null"><button type="default" plain="true" @click="chooseVideo">上传视频</button></view>
		<view class="" v-if="videoPath && videoShow">
            <video :src="videoPath" controls :show-center-play-btn="true"></video>
            <view class="">
                <button type="warn" size="mini" @click="videoPath=null">删除</button>
            </view>
        </view>
		<view class="lineH1"></view>

		<button type="primary" @tap="createParams('0')" :disabled="buttonDisable" v-if="eventId === null && hiddenButton!=3 && Lhidden">保存草稿</button>
		<button type="primary" @tap="createParams('2')" :disabled="buttonDisable" v-if="hiddenButton==1 || hiddenButton ==3 && Lhidden">当场办理</button>
		<button type="primary" @tap="createParams('1')" :disabled="buttonDisable" v-if="hiddenButton==2 || hiddenButton ==3  && Lhidden">上报网格长</button>
		<mpvue-picker
			:themeColor="themeColor"
			ref="mpvuePicker"
			:mode="mode"
			:deepLength="deepLength"
			:pickerValueDefault="pickerValueDefault"
			@onConfirm="onConfirm"
			@onCancel="onCancel"
			:pickerValueArray="pickerValueArray"
		></mpvue-picker>
	</view>
</template>

<script>
import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
import amap from '../../../common/amap-wx.js';
export default {
	components: { mpvuePicker },
	data() {
		return {
			list: [
				{
					title: '事件类型',
					value: [{ label: '请选择', value: '' },{ label: '企业事件', value: 1 }, { label: '普通事件', value: 2 }, { label: '应急事件', value: 3 }],
					selectedLabel: '请选择',
					selectedValue: '0'
				},
				{ title: '任务类型', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '涉事对象', value: null, selectedLabel: '请选择', selectedValue: '0' },
				{ title: '问题类型', value: null, selectedLabel: '请选择', selectedValue: '0' }
			],
			themeColor: '#007AFF',
			pickerValueDefault: [0],
			mode: '',
            address:'选择地址位置',
			pickerValueArray: [],
			selectIndex: '',
			imageList: [],
			videoPath: null,
			eventTitle: '',
			eventDesc: '',
			uploadFileHeader: {},
			location: null,
			eventId: null,
			hiddenButton: true,
			deepLength: 1,
			videoShow: true,
            buttonDisable:false,
            Lhidden : true,

			// {title:"企业",value:null,selectedLabel:"请选择",selectedValue:"0"},

			amapPlugin: null,
			mapKey: 'fbb5ddc12d6183eba23f27639f49757a'
		};
	},
	onLoad(event) {
		console.log('这是用户信息 ' + getApp().globalData.userInfo);
        this.hiddenButton = event.btn;
        if(event.btn == 1) {
	        uni.setNavigationBarTitle({
		        title: '当场办理'
	        });
        }
		var that = this;
		uni.getStorage({
			key: 'accessToken',
			success: function(res) {
				// console.log("存储的token333333  " + res.data);
				that.uploadFileHeader = { scpid: 'bearer.' + res.data };
				console.log('header:' + JSON.stringify(that.uploadFileHeader));
			},
			fail: function(error) {
				// console.log("main获取失败");
			}
		});

		if (event.id) {
			this.eventId = event.id;
			console.log('这里有id' + event.id);
			this.loadDraftData(event.id);
		}
	},
	methods: {
		seleceLocation() {
			var that = this;
			this.$eventHub.$on('fire', function(data) {
				console.log('消息回掉' + JSON.stringify(data));
				that.location = {
					latitude: data.latitude,
					longitude: data.longitude
				};
				that.address = data.address
				that.$eventHub.$off('fire');
			});
			if (that.location === null) {
				uni.navigateTo({
					url: '/pages/map/selectEventLocation/selectEventLocation'
				});
			} else {
				uni.navigateTo({
					url: '/pages/map/selectEventLocation/selectEventLocation?latitude=' + that.location.latitude + '&longitude=' + that.location.longitude
				});
			}
		},
		showPicker(index) {
			this.videoShow = false;
			let type = '';
			let id = '';
			let targetstype = '';
			if (this.list[index].title == '任务类型') {
				type = 'task_type';
			} else if (this.list[index].title == '涉事对象') {
				type = 'targets_type';
			}
			if (type.length > 0 && !this.list[index].value) {
				this.$http.get('ac/xagrid/appDictService/getDictItems', { type: type }).then(res => {
					this.list[index].value = res.data;
					this.list[index].value.unshift({ label: '请选择', value: '' })
					this.pickerValueArray = this.list[index].value;
					this.$refs.mpvuePicker.show();
				});
			} else {
				if (this.list[index].title == '企业' && !this.list[index].value) {
					//获取企业列表
					this.$http.get('ac/xagrid/appCompanyService/getCompanyItems', {}).then(res => {
						if (res.data.length == 0) {
							uni.showModal({
								title: '提示',
								content: '没有可选择的企业',
								showCancel: false
							});
						} else {
							this.list[index].value = res.data;
							this.pickerValueArray = this.list[index].value;
							this.$refs.mpvuePicker.show();
						}
					});
				} else if (this.list[index].title == '问题类型' && !this.list[index].value) {
					let self = this;
					if (self.list[0].selectedLabel == '企业事件') {
						id = self.list[3].selectedValue;
						targetstype = self.list[3].selectedValue;
						console.log('企业事件:' + id + '///' + targetstype);
					} else {
						id = self.list[2].selectedValue;
						targetstype = self.list[2].selectedValue;
						console.log('非企业事件:' + id + '///' + targetstype);
					}
					if (targetstype == '0') {
						uni.showModal({
							title: '提示',
							content: '请选择涉事对象',
							showCancel: false
						});
					} else {
						//获取涉事对象问题类型
						this.$http.post('as/xagrid/appdict/childrenList', { id: parseInt(id) }).then(res => {
							if (res.data.length == 0) {
								uni.showModal({
									title: '提示',
									content: '没有可选择的问题类型',
									showCancel: false
								});
							} else {
								this.list[index].value = res.data;
								this.pickerValueArray = this.list[index].value;
								this.$refs.mpvuePicker.show();
							}
						});
					}
				} else {
					this.pickerValueArray = this.list[index].value;
					this.$refs.mpvuePicker.show();
				}
			}
			this.selectIndex = index;
			this.mode = 'selector';
			this.pickerValueDefault = [0];
		},
		onConfirm(e) {
			this.videoShow = true;
			this.list[this.selectIndex].selectedLabel = e.label;
			this.list[this.selectIndex].selectedValue = e.value;
			if (e.label == '普通事件' && this.list[1].title === '企业') {
				//如果是普通事件 删除企业类型
				this.list.splice(1, 1);
			} else if (e.label == '应急事件' && this.list[1].title === '企业') {
				//如果是普通事件 删除企业类型
				this.list.splice(1, 1);
			} else if (
				e.label == '水污染' ||
				e.label == '散乱污' ||
				e.label == '大气污染' ||
				e.label == '噪声污染' ||
				e.label == '废水污染' ||
				e.label == '固废污染' ||
				e.label == '辐射污染' ||
				e.label == '废气污染' ||
				e.label == '生态环境污染' ||
				e.label == '其他污染'
			) {
				if (this.list[1].title === '企业') {
					this.list.splice(4, 4);
					this.list.splice(5, 4, { title: '问题类型', value: '', selectedLabel: '请选择', selectedValue: '0' });
				} else {
					this.list.splice(3, 3);
					this.list.splice(4, 3, { title: '问题类型', value: '', selectedLabel: '请选择', selectedValue: '0' });
				}
			} else if (e.label == '企业事件' && this.list[1].title !== '企业') {
				this.list.splice(1, 0, { title: '企业', value: '', selectedLabel: '请选择', selectedValue: '0' });
			}
		},
		onCancel() {
			this.videoShow = true;
		},
		previewImage(index) {
			//预览图片
			uni.previewImage({
				current: this.imageList[index],
				urls: this.imageList
			});
		},
		close(e) {
			this.imageList.splice(e, 1);
		},
		chooseImg() {
			//选择图片
			uni.chooseImage({
				sourceType: ['camera', 'album'],
				sizeType: 'compressed',
				count: 6 - this.imageList.length,
				success: res => {
					this.imageList = this.imageList.concat(res.tempFilePaths);
					console.log(JSON.stringify(res));
				}
			});
		},
		//选择视频
		chooseVideo() {
			var self = this;
			uni.chooseVideo({
				sourceType: ['camera', 'album'],
				success: function(res) {
					self.videoPath = res.tempFilePath;
				}
			});
		},
		bindInputBlur(e) {
            this.Lhidden = true
			this.eventTitle = e.detail.value;
			console.log('事件标题' + this.eventTitle);
		},
		bindTextAreaBlur(e) {
            this.Lhidden = true
			this.eventDesc = e.detail.value;
			console.log('事件描述' + this.eventDesc);
		},
        hiddenText:function(){
            this.Lhidden = false
        },
        //按钮设置不可以点击状态
        buttonFun(){
			this.buttonDisable = !this.buttonDisable
        },
		// 处理参数
		createParams(status) {
			this.buttonFun()
			var that = this;
			var params = new Object();
			//校验数据
			for (var i = 0; i < this.list.length; i++) {
				var item = this.list[i];
				if (item.selectedLabel === '请选择') {
					uni.showModal({
						title: '提示',
						content: '请选择' + item.title,
						showCancel: false
					});
                    this.buttonFun()
					return;
				} else {
					if (item.title === '事件类型') {
						params.eventType = String(item.selectedValue);
					} else if (item.title === '企业') {
						params.companyId = String(item.selectedValue);
					} else if (item.title === '任务类型') {
						params.taskType = String(item.selectedValue);
					} else if (item.title === '涉事对象') {
						params.targets_type = String(item.selectedValue);
					} else if (item.title === '问题类型') {
						params.questionType = String(item.selectedValue);
					}
				}
			}
			if (that.eventTitle.length === 0) {
				uni.showModal({
					title: '提示',
					content: '请输入问题描述',
					showCancel: false
				});
                this.buttonFun()
				return;
			} else {
				params.questionTitle = that.eventTitle;
			}

			if (that.eventDesc.length === 0) {
				uni.showModal({
					title: '提示',
					content: '请输入详细说明',
					showCancel: false
				});
                this.buttonFun()
				return;
			} else {
				params.questionContent = that.eventDesc;
			}
			if (that.location === null) {
				uni.showModal({
					title: '提示',
					content: '请选择事件位置',
					showCancel: false
				});
							this.buttonFun()
				return;
			} else {
				params.eventLongitude = that.location.longitude;
				params.eventLatitude = that.location.latitude;
				params.event_address = that.address;
			}
			if (this.imageList.length == 0) {
				console.log(params);
				uni.showModal({
					title: '提示',
					content: '请上传照片',
					showCancel: false
				});
              this.buttonFun()
				return;
			}

			params.status = status;

			if (this.imageList.length > 0 || this.videoPath !== null) {
				uni.showToast({
					icon: 'none',
					title: '正在上传...',
					mask: true,
					duration: 2000
				});
			}

			if (this.imageList.length > 0) {
				console.log('上传图片开始');
				this.uploadImages(params);
			} else if (this.videoPath !== null) {
				console.log('上传视频开始');
				this.uploadVideo(params);
			} else {
				console.log('直接提交了');
				that.reportEvent(params);
			}
			console.log('走到这里了' + JSON.stringify(params));
		},
		uploadImages(params) {
			var that = this;
			var oldImages = new Array();
			var images = new Array();
			for (var i = 0; i < that.imageList.length; i++) {
				var img = that.imageList[i];
				console.log('图片地址' + img);
				console.log('是否包含前缀' + img.indexOf('http://image.tripln.top/gridfile'));
				if (img.indexOf('http://image.tripln.top/gridfile') == 0) {
					oldImages.push(img.substr(32));
				} else {
					images.push({ name: 'images-' + String(i), uri: img });
				}
			}
			console.log('图片地址：' + JSON.stringify(images));
			console.log('header里的' + JSON.stringify(oldImages));
			if (images.length > 0) {
				uni.uploadFile({
					url: 'http://grid.tripln.top/api/xagrid/upload',
					files: images,
					fileType: 'image',
					header: that.uploadFileHeader,
					success: res => {
						// _contentResult = JSON.parse(res.data); //转义字符 得到结果集
						console.log('上传图片成功' + res.data);

						var succData = JSON.parse(res.data);
						for (var i = 0; i < succData.data.length; i++) {
							oldImages.push(succData.data[i].path);
						}
						console.log(' 整理后图片地址' + oldImages);
						params.questionImg = oldImages.join(',');
						console.log('参数' + JSON.stringify(params));
						if (that.videoPath !== null) {
							that.uploadVideo(params);
						} else {
							that.reportEvent(params);
						}
					},
					fail: err => {
						console.log('uploadImage fail', err);
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				});
			} else {
				params.questionImg = oldImages.join(',');
				console.log('参数' + JSON.stringify(params));
				if (that.videoPath !== null) {
					that.uploadVideo(params);
				} else {
					that.reportEvent(params);
				}
			}
		},
		uploadVideo(params) {
			var that = this;
			if (that.videoPath.indexOf('http://image.tripln.top/gridfile') == 0) {
				var path = that.videoPath.substr(32);
				params.questionVideo = path;
				that.reportEvent(params);
			
			} else {
				uni.showLoading({title:'开始上传视频...'})
				uni.uploadFile({
					url: 'http://grid.tripln.top/api/xagrid/upload',
					fileType: 'video',
					filePath: that.videoPath,
					header: that.uploadFileHeader,
					name: 'data',
					success: res => {
						console.log('上传视频成功' + res.data);
						var succData = JSON.parse(res.data);
						params.questionVideo = succData.data[0].path;
						uni.hideLoading();
						that.reportEvent(params);
					},
					fail: ret => {
						uni.showToast({
							title:JSON.stringify(ret),
							icon:'none'
						})
					}
				});
			}
		},
		reportEvent(params) {
			uni.showLoading({title:'开始提交事件...'})
			//上传
			var url;
			if (this.eventId !== null) {
				//草稿箱提报
				url = 'ac/xagrid/appEventServiceImpl/updateEvent';
				params.id = this.eventId;
			} else {
				//新事件提报
				url = 'ac/xagrid/appEventServiceImpl/addEvent';
			}
			this.$http.post(url, params).then(res => {
				uni.hideLoading();
				if (res.errcode === '0') {
					var tipStr;
					if (params.status === '0' || params.status === '2') {
						tipStr = '保存成功';
					} else {
						tipStr = '上报成功';
					}
					uni.showToast({
						title: tipStr,
						duration: 1500,
						complete() {
							setTimeout(function() {
								uni.navigateBack({});
							}, 1500);
						}
					});
				} else {
                  this.buttonFun()
					uni.showModal({
						title: '提示',
						content: res.errmsg,
						showCancel: false
					});
				}
			});
		},
		//草稿箱回显
		loadDraftData(id) {
			var self = this;
			this.$http.get('ac/xagrid/appEventServiceImpl/selectDraftsDetail', { id: id }).then(res => {
				self.eventDesc = res.data.questionContent;
				self.eventTitle = res.data.questionTitle;
				if (res.data.questionImg) {
					var images = res.data.questionImg.split(',');
					for (var i = 0; i < images.length; i++) {
						images[i] = 'http://image.tripln.top/gridfile' + images[i];
					}
					self.imageList = images;
					console.log('请求到的图片数组', JSON.stringify(self.imageList));
				}
				if (res.data.questionVideo) {
					var videoP = 'http://image.tripln.top/gridfile' + res.data.questionVideo;
					self.videoPath = videoP;
				}
				if (res.data.eventType === '1') {
					self.list[0].selectedValue = '1';
					self.list[0].selectedLabel = '企业事件';
					self.list[1].selectedValue = res.data.companyId;
					self.list[1].selectedLabel = res.data.companyName;
					self.list[2].selectedValue = res.data.taskType;
					self.list[2].selectedLabel = res.data.taskTypeName;
					self.list[3].selectedValue = res.data.targets_type;
					self.list[3].selectedLabel = res.data.targets_type_name;
					self.list[4].selectedValue = res.data.questionType;
					self.list[4].selectedLabel = res.data.questionTypeName;
				} else {
					self.list[0].selectedValue = '2';
					self.list[0].selectedLabel = '普通事件';
					// self.list.splice(1,1);
					self.list[1].selectedValue = res.data.taskType;
					self.list[1].selectedLabel = res.data.taskTypeName;
					self.list[2].selectedValue = res.data.targets_type;
					self.list[2].selectedLabel = res.data.targets_type_name;
					self.list[3].selectedValue = res.data.questionType;
					self.list[3].selectedLabel = res.data.questionTypeName;
				}
				self.location = { latitude: res.data.eventLatitude, longitude: res.data.eventLongitude };
			});
		}
	}
};
</script>

<style>
.viewBg {
	width: 100%;
	height: 100%;

	/* background-color: #0FAEFF; */
}

.cell-detail {
	margin-right: 20upx;
}
.uni-list-cell-navigate {
	justify-content: space-between;
}
.lineH20 {
	height: 20upx;
	/* width: 100%; */
	background-color: #f7f7f7;
}
.lineH1 {
	height: 2upx;
	/* width: 100%; */
	margin-left: 10upx;
	background-color: #f7f7f7;
}
.close-view {
	text-align: center;
	line-height: 14px;
	height: 16px;
	width: 16px;
	border-radius: 50%;
	background: #ff5053;
	color: #ffffff;
	position: absolute;
	top: -6px;
	right: -4px;
	font-size: 12px;
}
.button-sp-area {
	width: 40%;
}

map {
	width: 100%;
	height: 350upx;
	margin-top: 10upx;
	position: relative;
}

button {
	/* margin-top: 30upx; */
	/* margin-bottom: 30upx; */
	margin: 30upx;
}
</style>
